package cn.com.rocketmq.order;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.logging.org.slf4j.Logger;
import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 顺序消息生产者
 */
public class Producer {

    /**
     * 日志对象
     */
    private static  final Logger logger = LoggerFactory.getLogger(Producer.class);

    public static void main(String[] args) {
        DefaultMQProducer producer = null;
        try {
            producer = new DefaultMQProducer("orderProducer");
            producer.setNamesrvAddr("192.168.113.101:9876");
            producer.start();
            //i 队列序号
            for (int i = 0; i < 5; i++) {
                //j 消息序号
                for (int j = 0; j < 100; j++) {
                    Message message = new Message("rocketmq_orderDemo", "tag", ("Hello world!" + j).getBytes("UTF-8"));
                    producer.send(message, new MessageQueueSelector() {
                        /**
                         *
                         * @param list 队列集合
                         * @param message 消息 （send函数第一个参数）
                         * @param o 队列序号 （send函数第三个参数）
                         * @return 消息队列
                         */
                        @Override
                        public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                            return list.get(Integer.parseInt(o.toString()));
                        }
                    }, i);
                }
            }
        } catch (Exception e) {
            logger.error("消息发送失败！", e);
        } finally {
            if (producer != null) {
                producer.shutdown();
            }
        }
    }
}
